// pages/myMoney/myMoney.js
const app = getApp();
var aes = require('../../utils/aes.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    balance: 0, //钱包金额
    notReceivedBalance: 0,
    totalPrice : 0,
    second: 60,
    isResend: false,
    showIpt: false,
    userInfo: {},
    leftCount: 5, //提现多少次
    search: {
      pageNumber: 1,
      pageSize: 1
    },
    withdraw: { amount: '' },
    isFaceAuth: false,
    hasCertification: 8, //是否人脸识别
    isWindowNot: false,
    isWindowNo1: false,
    isWindowNo: false,
    uid: '',
    serveMoney: 0.00, //服务费
    aogMoney: 0.00, //到账金额
    qian: '',
    hou: ''
  },
  handleGoBtn() {
    this.toggle("isWindowNo", false)
    this.toggle("isWindowNo1", false)
  },
  handleCloseApp() {
    this.toggle("isWindowNot", false)
    this.toggle("isWindowNo", false)
    this.toggle("isWindowNo1", false)
  },
  handleIsAccredit() { //判断是否人脸识别
    var that = this
    app.req({
      url: "wechat/wxpay/faceAuthFlag",
      data: {
        uid: that.uid
      },
      success: res => {
        if (res.code == 200) {
          that.toggle('hasCertification', res.data.faceAuthFlag)
        }
      }
    });
  },
  sendCode() {
    var that = this
    if(that.data.withdraw.amount == ''){
      wx.showToast({
        title: '未输入提现金额',
        icon:'none'
      })
      return false
    }
    if(that.data.leftCount == 0){
      wx.showToast({
        title: '今日提现次数已达上限',
        icon:'none'
      })
      return false
    }
    if (that.data.balance<0.3 || Number(that.data.withdraw.amount)> Number(that.data.balance)){
      wx.showToast({
        title: '钱包余额不足',
        icon:'none'
      })
    } else{
    if (!that.data.isResend) {
      var param = that.data.withdraw;
      var url = "wechat/sys/sendCode?telphone=" + param.phone + "&type=3"
      app.req({
        url: url,
        method:"post",
        success: function (res) {
          if (200 == res.code) {
            that.toggle("isResend", true)
            var timer = setInterval(function () {
              that.toggle("second", --that.data.second)
              if (that.data.second < 0) {
                clearInterval(timer)
                that.toggle("isResend", false)
                that.toggle("second", 60)
              }
            }, 1000)
          }else {
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      });
    }
    }
  },
  showIpt() {
    var that = this
    if (that.data.showIpt) {
      var success = that.validate();
      if (success) {
        console.log('加密前', that.data.withdraw.amount)
        // var getamountPrice = that.data.withdraw.amount;
        // var balanceCha = Number(that.data.balance) - Number(that.data.withdraw.amount)
        // var income = Number(that.data.withdraw.amount) * 0.006 //服务费
        // if(income <0.1 ){
        //   income = 0.1
        // }
        // if (balanceCha < income ) {
        //   if( income >  0.1){
        //     var getamountPrice = (Number(that.data.withdraw.amount) - income).toFixed(2);  
        //   }else{
        //     var income = 0.1
        //     var getamountPrice = (Number(that.data.withdraw.amount) - 0.1).toFixed(2); 
        //   }
        // }
        // console.log('加密', getamountPrice)
        var getamount = that.getWithdraw(that.data.withdraw.amount);
        app.req({
          url: "wechat/wxpay/withdrawToChange",
          method: 'post',
          data: {
            amount: getamount,
            checkCode: that.data.withdraw.checkCode,
            phone: that.data.withdraw.phone
          },
          success: function (res) {
            if (res.code == 200) {
              wx.showToast({
                title: '提现成功',
                icon: 'success',
                duration: 1500
              })
              setTimeout(()=>{
                that.toggle("withdraw.checkCode", '')
                that.toggle("withdraw.amount", '')
                that.toggle("showIpt", false)
                // clearInterval(timer)
                that.toggle("isResend", false)
                that.toggle("second", 60)
                that.detail();
                that.balance();
                // that.refreshData();
              },1500)
            }else{
              wx.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
              })   
            }
          }
        });
      }
    } 
      else {
        //展开提现
        if (that.data.hasCertification == 1) { //人脸识别成功
          that.toggle("showIpt", true)
        } else if (that.data.hasCertification == 0) { //未进行实名认证
          that.toggle("isWindowNot", true)
        } else if (that.data.hasCertification == 2) { //识别次数超过3次
          that.toggle("isWindowNo", true)
        } else if (that.data.hasCertification == 3) { //投诉
          that.toggle("isWindowNo1", true)
        }
      }
  },
  validate: function () {
    var amount = this.data.withdraw.amount;
    var text = "";
    if (this.data.balance * 1 < 0.3) {
      text = "钱包余额不足";
    } else if (!amount && 0 != amount) {
      text = "提现金额不能为空";
    } else if (0 == amount) {
      text = '提现金额不能低于0.3元'
    } else if (0.3 > amount) {
      text = "提现金额不能低于0.3元";
    } else if (amount * 1 > this.data.balance) {
      text = "提现金额不能高于余额";
    } else if (amount > 5000) {
      text = "提现金额不能高于5000元";
    } else if (this.data.leftCount == 0) {
      text = "今日提现次数已达上限";
    } else if (!this.data.withdraw.checkCode) {
      text = "验证码不能为空";
    }
    if (!!text) {
      wx.showToast({
        title: text,
        icon: 'none',
        duration: 2000
      })
      return false;
    } else {
      return true;
    }
  },
  onCodeChange: function (e) {
    this.toggle("withdraw.checkCode", e.detail.value);
  },
  customBalanceChange(e) {
    var that = this
    e.detail.value = e.detail.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    e.detail.value = e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');

    if (e.detail.value.indexOf(".") < 0 && e.detail.value != "") {
      e.detail.value = parseFloat(e.detail.value);
    } else if (e.detail.value.indexOf(".") == 0) {
      // console.log(1111111111111111111111111111)
      e.detail.value = e.detail.value.replace(/[^$#$]/g, "0.");
      e.detail.value = e.detail.value.replace(/\.{2,}/g, ".");
    }
    if (e.detail.value > 5000) {
      e.detail.value = 5000
    }
    this.toggle("withdraw.amount", e.detail.value);
    
    if (Number(that.data.balance) > Number(e.detail.value)) { //非全部提现服务费
      // var priceCha = Number(that.data.balance) - Number(e.detail.value) //剩余金额
      var priceCha = that.sub(Number(that.data.balance),Number(e.detail.value))
      console.log(priceCha)
      var aog = Number(e.detail.value)
      var serve = Number(e.detail.value) * 0.006
      if(serve <0.1 ){
        serve = 0.1
      }
      if (priceCha < serve) { //余额不够
        if (serve > 0.1) {
          var aog = Number(e.detail.value) - serve;
        } else {
          var serve = 0.1;
          var aog = Number(e.detail.value) - 0.1;
        }
      }
      that.toggle("aogMoney", aog.toFixed(2));
      that.toggle("serveMoney", serve.toFixed(2));
    } else {
      if (Number(that.data.balance) > 0.3) { //全部提现服务费
        // var aog = Number(that.data.balance) * 0.994
        var serve = Number(that.data.balance) * 0.006
        var aog =  that.data.balance - serve.toFixed(2)
        if (serve < 0.1) {
          serve = 0.1
          aog = Number(that.data.balance) - 0.1
        }
        that.toggle("aogMoney", aog.toFixed(2));
        that.toggle("serveMoney", serve.toFixed(2));
      }else if(Number(that.data.balance) < 0.3 || Number(e.detail.value) < 0.3){
        that.toggle("aogMoney", 0);
        that.toggle("serveMoney", 0);
      }
    }
  },
  sub(a,b){
    var that = this;
    var c, d, e;
  try {
    c = a.toString().split(".")[1].length;
  } catch (f) {
    c = 0;
  }
  try {
    d = b.toString().split(".")[1].length;
  } catch (f) {
    d = 0;
  }
  return e = Math.pow(10, Math.max(c, d)), (that.mul(a, e) - that.mul(b, e)) / e;

},
mul(a, b) {
  var c = 0,
    d = a.toString(),
    e = b.toString();
  try {
    c += d.split(".")[1].length;
  } catch (f) {}
  try {
    c += e.split(".")[1].length;
  } catch (f) {}
  return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
},
  onAmountChange: function (e) {
    this.toggle("withdraw.amount", e.detail.value);
  },
  toggle(type, val) {
    this.setData({
      [type]: val
    });
  },
  toPage(e) {
    var dataset = e.currentTarget.dataset;
    var url = dataset.turn
    wx.navigateTo({
      url: url
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.uid = wx.getStorageSync('uid');
    this.refreshData();
    // if (this.uid) {
    //   this.handleIsAccredit() //判断是否人脸识别
    // }
  },

  refreshData: function () {
    var that = this;
    app.getUserInfo(function (userInfo) {
      that.toggle("search.uid", userInfo.id);
      that.toggle("withdraw.uid", userInfo.id);
      that.toggle("withdraw.phone", userInfo.telphone);
      that.detail();
      that.balance();
    });
  },
  refreshData1: function () {
    var that = this;
    app.getUserInfo(function (userInfo) {
      that.toggle("search.uid", userInfo.id);
      that.toggle("withdraw.uid", userInfo.id);
      that.toggle("withdraw.phone", userInfo.telphone);
      // that.detail();
      that.balance();
    });
  },
  detail: function () {
    var that = this;
    app.req({
      url: "wechat/sys/userSendCodeNum",
      method: "post",
      data : {},
      success: function (res) {
        if (200 == res.code) {
          that.toggle("leftCount", 5 - res.data.cashWithdrawal);
        }
      }
    });
  },
  balance: function () {
    var that = this;
    app.req({
      url: "wechat/account/expenseCalendars",
      method: "post",
      data: that.data.search,
      success: function (res) {
        if (200 == res.code) {
          var notReceivedBalance = res.data.notReceivedBalance || 0;
          var balance = res.data.balance || 0;
          var totalPrice = notReceivedBalance +   balance || 0.00;
          if(totalPrice > 0){
            totalPrice =  totalPrice.toFixed(2)
            var ab_str = totalPrice.toString();
            var ab_num = parseInt(ab_str.substring(0,ab_str.indexOf('.')));
            const s = totalPrice.replace(/\d+\.(\d*)/, '$1')
            that.toggle("hou", s);
          }
      
          if(balance > 0){
            balance = balance.toFixed(2)
          }
          if(notReceivedBalance > 0){
            notReceivedBalance = notReceivedBalance.toFixed(2)
          }
          // console.log(totalPrice)
          that.toggle("notReceivedBalance", notReceivedBalance);
          that.toggle("balance", balance);
          that.toggle("totalPrice", totalPrice);
          that.toggle("qian", ab_num);
         
          // if (Number(balance) > 0) { //全部提现服务费
          //   var aog = Number(that.data.balance) * 0.994
          //   var serve = Number(that.data.balance) * 0.006
          //   if (serve < 0.1) {
          //     serve = 0.1
          //     aog = Number(balance) - 0.1
          //   }
          //   that.toggle("aogMoney", aog.toFixed(2));
          //   that.toggle("serveMoney", serve.toFixed(2));
          // }
        }
      }
    });
  },
  getWithdraw: function (v) {
    var srcs = aes.CryptoJS.enc.Utf8.parse(new Date() + "|" + v);
    var key = aes.CryptoJS.enc.Utf8.parse("yiqilaiwang@1012");
    var encrypted = aes.CryptoJS.AES.encrypt(srcs, key, {
      mode: aes.CryptoJS.mode.ECB,
      padding: aes.CryptoJS.pad.Pkcs7
    });
    return encrypted.toString();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.refreshData1();
    this.handleIsAccredit();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.refreshData1();
    this.handleIsAccredit();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})